<script setup lang="ts">
defineOptions({
  name: "baseInfo"
});
import { ref, reactive, onMounted, markRaw, computed, customRef } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import dayjs from "dayjs";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { queryFileList } from "@/api/modules/fab";
import { getTableData } from "@/api/system/positionManage";
import { detectorIsolateTypeMap } from "@/views/gas/utils";

interface RuleForm {
  taskType: string;
  location: string;
  startTime: string;
  endTime: string;
  remark: string;
  fileIdList: Array<any>;
}

interface ListItem {
  value: string;
  label: string;
  [key: string]: any;
}

interface Props {
  data: Record<string, any>;
}

const taskTypeOptions = Array.from(detectorIsolateTypeMap)?.map(m => ({ value: m[0], label: m[1] }));

const defaultProps = {
  children: "children",
  label: "name"
};

const props = withDefaults(defineProps<Props>(), {
  data: () => null
});

const baseInfoRuleForm = defineModel({
  type: Object,
  default: () => ({
    taskType: "",
    location: "",
    startTime: "",
    endTime: "",
    remark: "",
    fileIdList: () => []
  })
});

const emits = defineEmits(["change"]);

const locationOptions = ref<Array<ListItem>>([]);
const baseInfoRuleFormRef = ref<FormInstance | null>(null);
const realFileList = ref<Array<any>>([]);
const fileList = ref<Array<any>>([]);
//  图片上传类型add：新增，edit：编辑，view：查看
const uploadType = ref<string>("add");

const baseInfoRules = reactive<FormRules<typeof baseInfoRuleForm.value>>({
  taskType: [{ required: true, message: "请选择隔离类型", trigger: ["blur", "change"] }],
  location: [{ required: false, message: "请选择施工位置", trigger: ["blur", "change"] }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: ["blur", "change"] }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: ["blur", "change"] }],
  remark: [{ required: false, message: "请输入备注信息", trigger: ["blur", "change"] }],
  fileIdList: [{ required: false, message: "请上传文档", trigger: ["blur", "change"] }]
});

const queryLocationTreeDataFn = async () => {
  locationOptions.value.splice(0);
  const params = {};
  const res = await getTableData(params);
  if (!res?.length) return;
  locationOptions.value.push(...res);
};

const queryFileListFn = async () => {
  const { fileIdList: ids = [] } = baseInfoRuleForm.value;
  if (!ids?.length) return;
  const params = { ids };
  const res = await queryFileList(params);
  if (!res?.length) return;
  fileList.value = res;
};

const startDisabledDateFn = (d: Date) => {
  const currentTimeStamp = Date.now();
  const timeStamp = new Date(d).getTime();
  if (timeStamp < currentTimeStamp - 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (timeStamp > currentTimeStamp + 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (baseInfoRuleForm.value.endTime && timeStamp > dayjs(baseInfoRuleForm.value.endTime).valueOf()) return true;
  return false;
};

const endDisabledDateFn = (d: Date) => {
  const currentTimeStamp = Date.now();
  const timeStamp = new Date(d).getTime();
  if (timeStamp < currentTimeStamp - 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (timeStamp > currentTimeStamp + 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (baseInfoRuleForm.value.startTime && timeStamp < dayjs(baseInfoRuleForm.value.startTime).valueOf()) return true;
  return false;
};

const validate = (): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    if (!baseInfoRuleFormRef.value) return reject(false);
    baseInfoRuleFormRef.value.validate(valid => {
      if (valid) {
        resolve(markRaw(baseInfoRuleForm.value));
      } else {
        reject(false);
      }
    });
  });
};

const reset = () => {
  if (!baseInfoRuleFormRef.value) return;
  baseInfoRuleFormRef.value.resetFields();
};

const changeFileListHandler = (fl: Array<any>) => {
  baseInfoRuleForm.value.fileIdList = [];
  if (!fl?.length) return;
  baseInfoRuleForm.value.fileIdList = fl.map(item => item.id);
  emitChangeHandler();
};

const getParams = () => {
  return { ...baseInfoRuleForm.value };
};

const emitChangeHandler = () => {
  const params = getParams();
  emits("change", params);
};

const init = async () => {
  await queryLocationTreeDataFn();
  await queryFileListFn();
};

onMounted(async () => {
  await init();
});

defineExpose({
  realFileList,
  baseInfoRuleFormRef,
  baseInfoRuleForm,
  validate,
  reset
});
</script>

<template>
  <px-form
    ref="baseInfoRuleFormRef"
    :model="baseInfoRuleForm"
    :rules="baseInfoRules"
    label-width="120px"
    class="base-info-form"
    scroll-to-error
    :scroll-into-view-options="{ behavior: 'smooth' }"
    status-icon
  >
    <px-row :gutter="24">
      <px-col :span="6">
        <px-form-item label="隔离类型" prop="taskType">
          <px-select v-model="baseInfoRuleForm.taskType" clearable filterable placeholder="请选择隔离类型">
            <px-option v-for="item in taskTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>

      <px-col :span="6">
        <px-form-item label="施工位置" prop="location" :required="baseInfoRuleForm.taskType === 'CONSTRUCTION'">
          <px-tree-select
            v-model="baseInfoRuleForm.location"
            :data="locationOptions"
            clearable
            filterable
            node-key="id"
            accordion
            highlight-current
            :props="defaultProps"
            placeholder="请选择施工位置"
            @change="emitChangeHandler"
          />
        </px-form-item>
      </px-col>

      <px-col :span="6">
        <px-form-item label="开始时间" prop="startTime">
          <px-date-picker
            v-model="baseInfoRuleForm.startTime"
            clearable
            type="datetime"
            :editable="false"
            format="YYYY/MM/DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="startDisabledDateFn"
            placeholder="请选择开始时间"
            @change="emitChangeHandler"
          />
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="结束时间" prop="endTime">
          <px-date-picker
            v-model="baseInfoRuleForm.endTime"
            clearable
            type="datetime"
            :editable="false"
            format="YYYY/MM/DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            :disabled-date="endDisabledDateFn"
            placeholder="请选择结束时间"
            @change="emitChangeHandler"
          />
        </px-form-item>
      </px-col>
      <px-col :span="24">
        <px-form-item label="备注" prop="remark">
          <px-input
            v-model.trim="baseInfoRuleForm.remark"
            :rows="2"
            type="textarea"
            maxlength="1000"
            show-word-limit
            clearable
            placeholder="请输入备注信息"
            @change="emitChangeHandler"
          />
        </px-form-item>
      </px-col>
      <px-col :span="24">
        <px-form-item label="" :label-width="0" prop="fileIdList" class="item-upload">
          <FileUpload :fileType="uploadType" :fileList="fileList" :countLimit="3" @changeFileList="changeFileListHandler" />
        </px-form-item>
      </px-col>
    </px-row>
  </px-form>
</template>

<style lang="scss" scoped>
.base-info-form {
  box-sizing: border-box;
  padding: 16px;
  padding-bottom: 0;

  .px-form-item {
    .px-select {
      width: 100%;
    }

    :deep(.px-date-editor) {
      width: 100%;
    }
  }

  :deep(.item-upload) {
    .px-form-item__content {
      margin-left: 0 !important;
    }
  }
}
</style>
